<?php

namespace App\Http\Controllers;
use function app\Common\formatDate;
use function app\Common\formatDate2;
use function app\Common\formatDate3;
use function app\Common\getFirstChar;
use function app\Common\headPic;
use function app\Common\secToTime;
use App\Events\Event;
use App\Events\WithDrawal;
use App\Models\Chat;
use App\Models\Room;
use App\Models\User;
use App\Models\Users;
use Encore\Admin\Grid\Filter\In;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;
use Intervention\Image\ImageManagerStatic as Image;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = Room::whereHas('users', function ($query) {
            $query->where('id','=',Auth::id());
        })->orderByDesc('sort')->orderBy('id')->get();
        foreach ($list as $k=>$v){
            $max = $v->chats()->max('time');
            $v->time=formatDate3($max);
            $word=$v->chats()->select('txt','user_name')->where('time','=',$max)->first();
            $other=$v->users()->where('id','<>',Auth::id())->first();
            if($v->users()->count()<=2){
                $v->personal = empty($v->pic)?1:0;
                $v->pic = empty($v->pic)?$other->headpic:$v->pic;
                $v->users()->count()==2?$v->name = $other->name:$v->name=Auth::user()->name;

                $v->lastWord=$word['txt'];
            }else{
                $v->personal=0;
                $v->lastWord = empty($word['txt'])?'':$word['user_name'].':'.$word['txt'];
            }
            $v->url = asset('uploads/'.$v->pic);
        }
        return view('home',[
            'list'=>$list,
        ]);
    }
    public function roomSort(){
        $roomId = Input::get('roomId');
        $room = Room::find($roomId);
        $sort = $room->sort;
        $room->sort = ($sort==1)?0:1;
        $room->save();
        return response()->json($room->sort);
    }
    public function roomDelete(){
        $roomId = Input::get('roomId');
        $room = Room::find($roomId);
        if($room->type==0){
            if($room->users()->count()==1){
                $room->users()->detach(Auth::id());
                $room->chats()->withTrashed()->forceDelete();
                $room->forceDelete();
                Storage::delete('uploads/'.$room->pic);
            }else{
                $pic_list=[];
                $users = $room->users()->where('id','<>',Auth::id())->get();
                foreach ($users as $v){
                    array_push($pic_list,asset('uploads/'.$v->headpic));
                }
                headPic($pic_list,$room->pic);
                $room->users()->detach(Auth::id());
                $room->main_id=$users[0]->id;
                $room->save();
            }
        }else{
            $room->delete();
            $room->chats()->delete();
        }
        broadcast(new Event(Auth::user(),'',-3,$roomId))->toOthers();
    }
    public function roomRename(){
        $user = Auth::user();
        $roomId = Input::get('roomId');
        $title = Input::get('title');
        $room = Room::find($roomId);
        $room->name = trim($title);
        $room->save();
        broadcast(new Event($user,$title,-1,$roomId))->toOthers();
        return response()->json($roomId);
    }
    public function getRoomMain(){
        $roomId = Input::get('roomId');
        $room = Room::find($roomId);
        $user = User::find($room->main_id);
        $user->notice=empty($room->notice)?'':$room->notice;
        $user->notice_time=empty($room->notice_time)?'':formatDate3($room->notice_time);
        $user->url = asset('uploads/'.$user->headpic);
        return response()->json($user);
    }
    public function editNotice(){
        $notice = Input::get('notice');
        $roomId = Input::get('roomId');
        $room = Room::find($roomId);
        $room->notice = $notice;
        $room->notice_time = time();
        $room->save();
    }
    public function chatList($id){
        $room = Room::find($id);
        $users=0;$isMain=0;$user=0;
        if($room->type==0){
            $main_id = $room->main_id;
            $isMain = Auth::id()==$main_id?1:0;
            $users = $room->users;
            foreach ($users as $v){
                $v->url = asset('uploads/'.$v->headpic);
            }
        }else{
            $user=$room->users()->where('id','<>',Auth::id())->first();
            $user->url = asset('uploads/'.$user->headpic);
        }
        if(Auth::user()->can('view chatHistory')){
            $list = $room->chats;
            foreach ($list as $v){
                $v->time=formatDate2($v->time);
                if($v->user_id!=Auth::user()->id){
                    $v->role='ans';
                }else{
                    $v->role='ask';
                }
                $v->url = asset('uploads/'.$v->user_headpic);
            }
        }else{
            $list='';
        }
        return response()->json([
            'room'=>$room,
            'users'=>$users,
            'user'=>$user,
            'list'=>$list,
            'isMain'=>$isMain
        ]);
    }

    public function userList(){
        $id=Input::get('id');
        $type = Input::get('type');
        if($type==1){
            $ids = Room::find($id)->users()->pluck('id');
            $user = User::whereNotIn('id',$ids)->orderBy('name')->get();
        }elseif($type==2){
            $user = Room::find($id)->users()->where('id','<>',Auth::id())->get();
        }else{
            $user = User::where('id','<>',Auth::id())->orderBy('name')->get();
        }
        foreach ($user as $v){
            $v->sort=getFirstChar($v->name);
            $v->url = asset('uploads/'.$v->headpic);
        }
        for($i=65;$i<=90;$i++){
            $v =$user->where('sort',chr($i));
            if(count($v)>0&&!empty($v)){
                $list[chr($i)]=$v;
            }
        }
        if(count($user->where('sort','#'))>0){
            $list['#']=$user->where('sort','#');
        }
        return response()->json($list);
    }

    public function reduceUsers(){
        $ids= Input::get('ids');
        $roomId = Input::get('roomId');
        $pic_list=[];
        $room = Room::find($roomId);
        $room->reduceUsers($ids);
        $users = $room->users;
        foreach ($users as $v){
            array_push($pic_list,asset('uploads/'.$v->headpic));
        }
        headPic($pic_list,$room->pic);
        $room->main_id=$users[0]->id;
        $room->save();
        //broadcast(new Event(Auth::user(),'',-3,$roomId))->toOthers();
        return response()->json($ids);
    }

    public function addUsers(){
        $id = Input::get('id');
        $type = Input::get('type');
        $ids = Input::get('ids');
        $pic_list=[];
        $room = Room::find($id);
        $room_ids = $room->users()->pluck('id');
        $coll_ids = collect([$ids, $room_ids])->collapse();
        $all_users = User::find($coll_ids);
        foreach ($all_users as $v){
            array_push($pic_list,asset('uploads/'.$v->headpic));
        }
        if($type==0){
            headPic($pic_list,$room->pic);
            $users = User::find($ids);
            foreach ($users as $v){
                $v->url = asset('uploads/'.$v->headpic);
            }
            $names = $users->pluck('name');
            $room->addUsers($ids);
            broadcast(new Event(Auth::user(),$names,-2,$id))->toOthers();
            return response()->json([
                'room'=>$room,
                'names'=>$names,
                'users'=>$users
            ]);
        }else{
            $headpic = time().random_int(10000,99999).'.jpeg';
            headPic($pic_list,$headpic);
            $room = Room::create(['main_id'=>Auth::id(),'name'=>'群聊','pic'=>'images/'.$headpic,'type'=>0,'sort'=>0]);
            $room->url = asset('uploads/'.$room->headpic);
            $room->syncUsers($coll_ids);
            return response()->json($room);
        }
    }

    public function createRoom(){
        $ids = Input::get('ids');
        $flag = true;
        if(count($ids)>1){
            $pic_list=[];
            array_push($ids,Auth::id());
            $users = User::find($ids);
            foreach ($users as $v){
                array_push($pic_list,asset('uploads/'.$v->headpic));
            }
            $headpic = time().random_int(10000,99999).'.jpeg';
            headPic($pic_list,$headpic);
            $room = Room::create(['main_id'=>Auth::id(),'name'=>'群聊','pic'=>'images/'.$headpic,'type'=>0,'sort'=>0]);
            $room->syncUsers($ids);
        }else{
            $user = User::find($ids[0]);
            array_push($ids,Auth::id());
            $roomIds = Room::whereNotNull('pic')->pluck('id');
            $user_room = DB::table('user_room')
                ->select(DB::raw('room_id,count(*) as num'))
                ->groupBy('room_id')
                ->where('room_id','<>','1')
                ->whereNotIn('room_id',$roomIds)
                ->whereIn('user_id',$ids)
                ->havingRaw('count(*) > 1')
                ->get();
            if(count($user_room)>0){
                $room_id=$user_room[0]->room_id;
                $room = Room::withTrashed()->find($room_id);
                if($room->trashed()){
                    $room->restore();
                    $room->name = $user->name;
                    $room->pic = $user->headpic;
                }else{
                    $flag=false;
                }
            }else{
                $room = Room::create(['name'=>'私聊','type'=>1,'sort'=>0]);
                $room->pic = $user->headpic;
                $room->syncUsers($ids);
                $room->name = $user->name;
            }
        }
        $room->url = asset('uploads/'.$room->pic);
        return response()->json([
            'flag'=>$flag,
            'room'=>$room,
        ]);
    }
    public function send(){
        $txt = Input::get('txt');
        $room_id = Input::get('roomId');
        $user = Auth::user();
        $user->url=asset('uploads/'.$user->headpic);
        $user->time = date('h:i');
        if(Input::ajax()){
            $dialogueId = Chat::insertGetId(['user_id'=>$user->id,'user_name'=>$user->name,'user_headpic'=>$user->headpic,'time'=>time(),'txt'=>$txt,'room_id'=>$room_id]);
            broadcast(new Event($user,$txt,$dialogueId,$room_id))->toOthers();
            return response()->json([
                'user'=>$user,
                'id'=>$dialogueId,
            ]);
        }
    }
    public function WithDrawal(){
        $dialogueId=Input::get('id');
        $user = Auth::user();
        $dialogue = Chat::withTrashed()->find($dialogueId);
        $interval=time()-$dialogue->time;
        $time=secToTime($interval);
        $flag=0;
        if(Input::ajax()){
            if($interval<120){
                $dialogue->forceDelete();
                $flag=1;
                broadcast(new WithDrawal($user,$dialogueId))->toOthers();
            }
            return response()->json([
                'user'=>$user,
                'time'=>$time,
                'flag'=>$flag
            ]);
        }
    }
    function getUserInfo(){
        if(Input::ajax()){
            $id = Input::get('id');
            $user = Users::find($id);
            $user->url = asset('uploads/'.$user->headpic);
            return response()->json([
                'user'=>$user
            ]);
        }
    }
    public function deleteDialogue(){
        $id= Input::get('id');
        $user = Auth::user();
        $isSoftDel= Input::get('isSoftDel');
        $dialogue = Chat::withTrashed()->find($id);
        $old=$dialogue->deleted_by;
        if($isSoftDel==1){
            if(!$old){
                $dialogue->deleted_by=$user->id;
            }else{
                $dialogue->deleted_by=$old.','.$user->id;
            }
            $dialogue->save();
            $dialogue->delete();
        }else{
            $dialogue->forceDelete();
        }
        return response()->json([
            'isSoftDel'=>$isSoftDel
        ]);
    }
    public function getHistory(){
        if(Auth::user()->can('view chatHistory')){
            $key = Input::get('txt');
            $page = Input::get('page');
            $size = Input::get('size');
            $roomId = Input::get('roomId');
            if(Input::ajax()){
                $skip = ($page-1)*$size;
                $dialogue = Chat::withTrashed()->where('txt','like','%'.$key.'%')->where('room_id',$roomId)->skip($skip)->take($size)->orderByDesc('time')->get();
                foreach ($dialogue as $v){
                    $v->time=formatDate($v->time);
                    $v->url = asset('uploads/'.$v->user_headpic);
                    $v->self = Auth::id()==$v->user_id?1:0;
                }
                return response()->json([
                    'dialogue'=>$dialogue
                ]);
            }
        }
    }
}
